﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
using Microsoft.MSE.Catalog.Contracts;
using System.ServiceModel.Channels;
using System.Threading;
using System.IO;
using System.Xml;
using System.Diagnostics;
using System.ServiceModel.Description;

namespace Microsoft.MSE.Catalog.Module
{
    public class NotificationManager : INotificationManager, IExtension<ServiceHostBase>
    {
        public delegate bool FilterTestDelagate(Subscription subscription, MseEventData eventData);

        protected FilterTestDelagate mMatchesFilter = null;
        protected string mFilterDialect = null;

        private ISubscriptionManager _subscriptionManager;

        public NotificationManager(ISubscriptionManager subscriptionManager)
        {
            _subscriptionManager = subscriptionManager;
            mFilterDialect = SC.MSEEventingFilterDialect;
            mMatchesFilter = this.MatchesFilterTest;
        }
        public virtual void RaiseEvent(MseEventData eventData)
        {
            lock (this)
            {
                Dictionary<Guid, Subscription> subscriptions = _subscriptionManager.GetSubscriptions();
                Dictionary<Guid, Subscription>.KeyCollection keys = subscriptions.Keys;

                foreach (Guid key in keys)
                {
                    Subscription subscription = subscriptions[key];
                    if (mMatchesFilter(subscription, eventData))
                    {
                        Notification notification = new Notification(eventData, subscription.notifyToAddress,
                                                                    subscription.notifyToAction,
                                                                    subscription.notifyToReferenceParameters,
                                                                    subscription.notifyToBinding);
                        Thread thread = new Thread(new ThreadStart(notification.SendOneWayNotification));
                        thread.Start();
                    }
                }
            }
        }


        protected virtual bool MatchesFilterTest(Subscription subscription, MseEventData eventData)
        {
            //match the subscription filter to the current event topic
            return subscription.filter.Equals(Enum.GetName(eventData.EventTopic.GetType(), eventData.EventTopic), StringComparison.InvariantCultureIgnoreCase);
        }

        #region IExtension<ServiceHostBase> Members

        public void Attach(ServiceHostBase owner)
        {
        }

        public void Detach(ServiceHostBase owner)
        {
        }

        #endregion
    }
}
